{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optimum.onnxruntime import ORTModelForFeatureExtraction\n",
    "from transformers import AutoTokenizer\n",
    "from transformers import Pipeline\n",
    "import torch.nn.functional as F\n",
    "import torch\n",
    "import numpy as np\n",
    "from sentence_transformers import SentenceTransformer\n",
    "import json\n",
    "import time\n",
    "from tqdm import tqdm\n",
    "from pathlib import Path\n",
    "from typing import List"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "onnx_path = Path(\"bge_chinese_large_v1d5_finetune_240129v2_onnx/\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load optimized model\n",
    "model = ORTModelForFeatureExtraction.from_pretrained(\n",
    "    onnx_path, file_name=\"model_optimized.onnx\", provider=\"CUDAExecutionProvider\"\n",
    ")\n",
    "tokenizer = AutoTokenizer.from_pretrained(onnx_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_id = \"bge_chinese_large_v1d5_finetune_240129v2\"\n",
    "sbertmodel = SentenceTransformer(model_id)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sbertoutput = sbertmodel.encode(\"你是谁\", normalize_embeddings=True)\n",
    "sbertoutput"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def embd_func(\n",
    "    model,\n",
    "    tokenizer,\n",
    "    inputs: List[str],\n",
    "    normalize_embeddings: bool = True,\n",
    "    max_length: int = 512,\n",
    ") -> np.ndarray:\n",
    "    encoded_inputs = tokenizer(\n",
    "        inputs,\n",
    "        padding=True,\n",
    "        truncation=True,\n",
    "        return_tensors=\"pt\",\n",
    "        max_length=max_length,\n",
    "    )\n",
    "    outputs = model(**encoded_inputs)\n",
    "\n",
    "    embedding_value = outputs.last_hidden_state[:, 0]\n",
    "    if normalize_embeddings:\n",
    "        # Normalize embeddings\n",
    "        sentence_embeddings = F.normalize(embedding_value, p=2, dim=1)\n",
    "\n",
    "    sentence_embeddings = sentence_embeddings.cpu().numpy()\n",
    "    return sentence_embeddings\n",
    "\n",
    "\n",
    "onnx_test = embd_func(model, tokenizer, [\"你是谁\", \"你是谁1\"])\n",
    "onnx_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "26988"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "with open(\"gptdataset/0.json\", encoding=\"utf-8\", mode=\"r\") as fin:\n",
    "    alldata = [json.loads(i) for i in fin.readlines()]\n",
    "\n",
    "allquery = [i[\"query\"] for i in alldata]\n",
    "len(allquery)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "alltime = []\n",
    "for i in tqdm(allquery[:500]):\n",
    "    s1 = time.time()\n",
    "    v = sbertmodel.encode(i, normalize_embeddings=True)\n",
    "    s1 = time.time() - s1\n",
    "    alltime.append(s1)\n",
    "np.mean(alltime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "alltime = []\n",
    "for i in tqdm(allquery[:500]):\n",
    "    s1 = time.time()\n",
    "    v = embd_func(model, tokenizer, [i])\n",
    "    s1 = time.time() - s1\n",
    "    alltime.append(s1)\n",
    "np.mean(alltime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sbert_test = sbertmodel.encode([\"你是谁\", \"你是谁1\"], normalize_embeddings=True)\n",
    "sbert_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.allclose(onnx_test, sbert_test, atol=1e-3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "onnx_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sbert_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
